package com.ellricky.baselib.ui.clue

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.andr.common.permission.PermissionManager
import com.andr.common.permission.Permissions
import com.andr.common.util.DialUtil
import com.andr.common.util.ToastUtil
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.R
import com.ellricky.baselib.adapter.CluePoolAdapter
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.dialog.picker.EPickerUtil
import com.ellricky.baselib.entity.IdNamePickerEntity
import com.ellricky.baselib.entity.new.CluePoolDetail
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.ui.base.BaseDetailActivity
import com.ellricky.baselib.ui.consutant.CtSelectActivity
import com.ellricky.baselib.ui.xufei.PriceAddActivity
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewECallback
import com.ellricky.baselib.util.jump
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.base_activity_clue_pool_detail.*
import java.util.*

class CluePoolDetailActivity : BaseDetailActivity() {

    private var intentId: String = ""//意向id
    private var remark: String = ""//
    private var schoolId: String = ""//市场端分配校区
    private var ePickerUtil: EPickerUtil? = null
    private var adapter: CluePoolAdapter? = null
    private var tel:String = ""
    private var intentList: ArrayList<IdNamePickerEntity> = arrayListOf(
        IdNamePickerEntity("28", "待办理"),
        IdNamePickerEntity("291", "有意向(A)"),
        IdNamePickerEntity("292", "有意向(B)"),
        IdNamePickerEntity("293", "有意向(C)"),
        IdNamePickerEntity("294", "有意向(D)"),
        IdNamePickerEntity("31", "无意向"),
    )

    override fun getContentLayout(): Int {
        return R.layout.base_activity_clue_pool_detail
    }

    override fun initUIView() {
        super.initUIView()
        mTvTitle.setText(R.string.base_clue_detail)
        ePickerUtil = EPickerUtil(this)

        btnPay.setOnClickListener(this)
        btnPay2.setOnClickListener(this)
        btnIntent!!.setOnClickListener(this)
        btnVisit.setOnClickListener(this)
        btnCon.setOnClickListener(this)
        btnSchool.setOnClickListener(this)
        ivCluePhone.setOnClickListener(this)
        initRvRecord()
        loadDetail(id)

        when (LocalCacheUtil.getCardType()) {
            BaseConstant.CARD_PRESIDENT -> {
                llSelectCon.visibility = View.VISIBLE
                llVisit.visibility = View.GONE
                llSchool.visibility = View.GONE
            }
            BaseConstant.CARD_CONSULTANT -> {
                llVisit.visibility = View.VISIBLE
                llSelectCon.visibility = View.GONE
                llSchool.visibility = View.GONE
            }
            BaseConstant.CARD_MARKET -> {
                llSchool.visibility = View.VISIBLE
                llSelectCon.visibility = View.GONE
                llVisit.visibility = View.GONE
            }
        }
    }

    private fun initRvRecord() {
        adapter = CluePoolAdapter(this)
        rvRecord!!.layoutManager = LinearLayoutManager(this)
        rvRecord.adapter = adapter
    }

    private fun loadDetail(id: String) {
        val url = EAppUtil.getApiHost()
        val paramMap = HashMap<String, String>()
        paramMap["action"] = "returnList"
        paramMap["clue_id"] = this.id
        paramMap["eid"] = LocalCacheUtil.getUid()
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewECallback<CluePoolDetail>(this) {
                override fun onSuccess(data: CluePoolDetail, msg: String?) {
                    tvName.value = data.clue_name
                    tvAge.value = data.clue_age
                    tvSex.value = data.clue_sex
                    tvTel.value = data.clue_tel
                    tvConsultant.value = data.input_name
                    tvTime.text = data.input_time
                    tvInput.value = data.input_name
                    tvClueFrom.value = data.from_name
                    tvRemark.value = data.remark
                    tvSchool.value = data.clue_schoolname
                    adapter?.refresh(data.return_list)
                    data.clue_is_apply.apply {
                        if (this == 1) {
                            llVisit.visibility = View.GONE
                        }
                    }
                    data.is_sale.apply {
                        if (this == 0) {
                            btnCon.text = "已分配课程顾问"
                            btnCon.setOnClickListener(null)
                        }
                    }
                }
            })

    }

    override fun onClickView(v: View) {
        super.onClickView(v)
        when (v.id) {
            R.id.btnIntent -> {
                ePickerUtil?.showIntentPicker(intentList, null) { _, t ->
                    intentId = t.id
                    if (intentId.isNotEmpty() && remark.isNotEmpty()) {
                        addIntent()
                    }
                }
            }
            R.id.btnPay -> {
                jump<PriceAddActivity> {
                    putExtra(BaseConstant.KEY_ID, id)
                    putExtra(BaseConstant.KEY_FROM, "student")
                }
            }
            R.id.btnPay2 -> {
                jump<PriceAddActivity> {
                    putExtra(BaseConstant.KEY_ID, id)
                    putExtra(BaseConstant.KEY_FROM, "student")
                }
            }
            R.id.btnVisit -> {
                XPopup.Builder(this)
                    .asInputConfirm("填写回访记录", "请填写回访记录") {
                        remark = it
                        if (intentId.isNotEmpty() && remark.isNotEmpty()) {
                            addIntent()
                        }
                    }.show()
            }
            //选择顾问 校长端选择
            R.id.btnCon -> {
                jump<CtSelectActivity> {
                    putExtra(BaseConstant.KEY_ID, id)
                }
            }
            R.id.btnSchool -> {
                ePickerUtil?.checkSchoolDate(null) { _, t ->
                    schoolId = t.id
                    addSchool()
                }
            }
            R.id.ivCluePhone -> {
                val phone = tvTel.value
                this.tel = phone
                dial()
            }
        }
    }

    private fun dial() {
        PermissionManager.getInstance()
            .setGrantResult(this)
            .requestPermissions(this, Permissions.CALL_PHONE)
    }

    override fun onGrantedAll() {
        super.onGrantedAll()
        DialUtil.dial(this, tel)
    }

    override fun onDenied(vararg permission: String) {
        super.onDenied(*permission)
        if (permission[0] == Permissions.CALL_PHONE) {
            ToastUtil.show(this, "请打开打电话权限")
        }
    }

    /**
     * 分配学校
     */
    private fun addSchool() {
        val url = EAppUtil.getApiHost()
        val paramMap = HashMap<String, String>()
        paramMap["action"] = "allotClueToSchool"
        paramMap["clue_ids"] = id
        paramMap["school_id"] = schoolId
        paramMap["eid"] = LocalCacheUtil.getUid()
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewECallback<Any>(this) {
                override fun onSuccess(data: Any, msg: String?) {
                    ToastUtil.show(this@CluePoolDetailActivity, "分配成功")
                    loadDetail(id)
                }
            })
    }

    private fun addIntent() {
        val url = EAppUtil.getApiHost()
        val paramMap = HashMap<String, String>()
        paramMap["action"] = "addReturn"
        paramMap["clue_id"] = id
        paramMap["return_state_dic_id"] = intentId
        paramMap["return_next_time"] = ""
        paramMap["return_remark"] = remark
        paramMap["eid"] = LocalCacheUtil.getUid()
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewECallback<Any>(this) {
                override fun onSuccess(data: Any, msg: String?) {
                    ToastUtil.show(this@CluePoolDetailActivity, "添加成功")
                    loadDetail(id)
                }
            })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == BaseConstant.RESULT_CODE_ADD) {
            // 刷新课程顾问
            loadDetail(id)
        }
    }
}